/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.prep.view.command;

import java.awt.Toolkit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import br.ufmg.dees.insane.commons.command.Command;
import br.ufmg.dees.insane.commons.view.ExtensionFileFilter;
import br.ufmg.dees.insane.model.prep.GeoPrepModel;
import br.ufmg.dees.insane.ui.rich.prep.view.DesktopPrep;

/**
 * This class is a implementation of the interface Command.
 * It's unabled to undo or redo.
 * It's called from the method "DesktopPrep.closeModel()".
 * Its "execute" method verify if the model has a file, and
 * if it has changes.
 *
 * @author Ferreira, Reginaldo & Pitangueira, Roque
 * @since 14/11/2006
 */
public class SaveOnExitCommand  implements Command {
    
    private DesktopPrep parent;
    private JFileChooser fileChooser;
    private ExtensionFileFilter filter = new ExtensionFileFilter("isn", "INSANE-PREP Files");
	private boolean validFile;
	private GeoPrepModel model;
	
//*****************************************************************************
	
    /**
     * Creates new SaveFileCommand
     * and sets the FileFilter do FileChooser.
     *
     * @param parent The JFrame parent.
     */
    public SaveOnExitCommand(DesktopPrep parent, GeoPrepModel mdl) {
        this.parent = (DesktopPrep)parent;
        this.model = mdl;
        fileChooser = new JFileChooser();
        fileChooser.setFileFilter(filter);
    }
	
//*****************************************************************************
	
    /**
     * Saves the current model accordding to ModelState name.
     * If ModelState has its initial name it prompts a dialog to
     * choose another name.
     *
     * @see gui.command.AAAcommand#execute()
     */ 
    public void execute()
    {	
    	if (model.hasFile() == false)
    	{ 
    		validFile = false;
    		while (!validFile)
    		{
    			File f =  new File(model.getName());
    			fileChooser.setSelectedFile(f);
    			
    			int retVal = fileChooser.showSaveDialog(parent);
    					
    			if (retVal == JFileChooser.APPROVE_OPTION)
    			{		
    				//Getting the file name
    				String s = fileChooser.getSelectedFile().getName();
    				
    				// Sets the model's name
    				model.setName(s);
 						
    				//Getting the file extension
    				String ext = new String();
    				int i = s.lastIndexOf('.');
    				if (i > 0 &&  i < s.length() - 1)
    				{
    					ext = s.substring(i+1).toLowerCase();
    				}
    						
    				//Comparing the extension
    				if (!ext.equals("isn"))
    				{
    					s = s + ".isn";
    					File file = fileChooser.getSelectedFile();
    							
    					//Changing the file in case of no good extensions
    					fileChooser.setSelectedFile(new File(file.getParent() + File.separator + s));
    				}

    						
    				//Checks if the file exists
    				if (fileChooser.getSelectedFile().exists())
    				{
    					int value = 10;
    					value = JOptionPane.showConfirmDialog(parent,
    						"File \"" + fileChooser.getSelectedFile().getPath() + "\" already exists." +
    						"\nDo you want to replace it?",
    						"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    					if (value == JOptionPane.YES_OPTION)
    					{ validFile = true; }
    				}
    				else
    				{ validFile = true; }
    			}// if
    		else return;
    	    }// end while
    		
			// Informs the model that its file exists
			model.setHasFile(true);
			// Informs the model that its file exists
			model.setIsModified(false);
			// Sets the model's path
			model.setPath(fileChooser.getSelectedFile().getPath());
			//Saves the file
    		this.save();
    		
		}// if has file
    	

    	if (model.isModified() == true) 
		{
    		model.setIsModified(false);
    		fileChooser.setSelectedFile(new File(model.getPath()));
    		this.save();
		}
    	
	}//end of method
    
//  ****************************************************************************
	
    /**
     * Writes model on disc using a FileOutputStream and 
     * an ObjectOutputStream.
     */
    private void save()
    {
    	try
    	{
    		FileOutputStream serialStream = new FileOutputStream(fileChooser.getSelectedFile());
            ObjectOutputStream stream = new ObjectOutputStream(serialStream);
            stream.writeObject((GeoPrepModel)model);
            serialStream.flush();
                
        	String path = fileChooser.getSelectedFile().getPath();
            parent.getDesktopTextArea().addText("The model was saved at:  " + path);
    	}
    	catch (Exception exc)
    	{
             Toolkit.getDefaultToolkit().beep();
             JOptionPane.showMessageDialog(parent, "Couldn't save file!", "Error Message", JOptionPane.ERROR_MESSAGE);
             parent.getDesktopTextArea().addText("Error: the model wasn't save!");
        }
    }

//  ***************************************************************************
	
    /**
     * Impossible to undo - not implemented.
     */
    public void undo() {}
    
//  ***************************************************************************
	
    /**
     * Impossible to redo - not implemented.
     */
    public void redo() {}
    
//  ***************************************************************************
}

